package org.zcl.config;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.zcl.pojo.Configuration;
import org.zcl.pojo.MapperStatement;

import java.io.InputStream;
import java.util.List;

/**
 * .
 *
 * @Author Chenglin Zhu
 * @Date 2022/3/12 18:19
 */
public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String nameSpace = rootElement.attributeValue("namespace");
        List<Element> list = rootElement.selectNodes("//select");
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("parameterType");
            String sqlText = element.getTextTrim(); // 去掉空格拿到标签内信息
            MapperStatement mapperStatement = new MapperStatement();
            mapperStatement.setId(id);
            mapperStatement.setResultType(resultType);
            mapperStatement.setParamterType(paramterType);
            mapperStatement.setSql(sqlText);
            String key = nameSpace + "." + id;
            configuration.getMapperStatementMap().put(key, mapperStatement);
        }
    }
}
